<?php


namespace App\HttpController;


use App\Component\Excel;
use App\Component\Jwt;
use App\Component\User;
use App\Core\BaseController;
use App\Core\Exception\DefaultException;
use App\Event\Event;
use App\Lib\Mongodb\Mongodb;
use App\Logic\Account\StatisticsService;
use App\Logic\Member\MemberProfitScoreService;
use App\Logic\Member\MemberProfitStatisticsService;
use App\Logic\Member\MemberScoreService;
use App\Logic\Member\MemberService;
use App\Logic\Order\OrderReturnedService;
use App\Logic\Order\OrderService;
use App\Logic\Order\OrderTaskService;
use App\Logic\Order\OrderTaskStatisticsService;
use App\Logic\Purchase\Form\SubmitPurchaseForm;
use App\Logic\Purchase\PurchaseService;
use App\Logic\Shipping\ShippingService;
use App\Model\Account\CashoutModel;
use App\Model\Order\OrderModel;
use App\Model\UserModel;
use App\Process\Task;
use App\Util\CommonHelper;
use EasySwoole\Component\Di;
use EasySwoole\Component\Timer;
use EasySwoole\ElasticSearch\RequestBean\PutScript;
use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ElasticSearch\ElasticSearch;
use EasySwoole\ORM\DbManager;
use EasySwoole\Utility\Time;
use MongoDB\Driver\BulkWrite;

use EasySwoole\Component\WaitGroup;
use EasySwoole\Tracker\PointContext;

class Index extends BaseController
{

    public function index()
    {
        $data = $this->getJson();
//        \EasySwoole\EasySwoole\Task\TaskManager::getInstance()->sync((new Task())->run(),10,1);
//        OrderService::getInstance()->createOrderAutoAccount($data);
//        AccpoolService::getInstance()->resetApOrder();
//        OrderService::getInstance()->orderProfit($data['id']);
        $this->writeJson(200, ["aaa" => 1], "success");
    }

    function test()
    {
        $data = $this->getJson();
        SubmitPurchaseForm::getInstance()->getGoods();
        // 示例数据
        $goods = [
            ['name' => '商品1', 'price' => 61.76],
            ['name' => '商品2', 'price' => 613.09],
            ['name' => '商品3', 'price' => 172.69],
            ['name' => '商品4', 'price' => 896.25],
            ['name' => '商品5', 'price' => 398.85],
            ['name' => '商品6', 'price' => 333.75],
            ['name' => '商品7', 'price' => 883.69],
            ['name' => '商品8', 'price' => 209.45],
            ['name' => '商品9', 'price' => 750.39],
            ['name' => '商品10', 'price' => 541.99],
        ];

        $totalAmount = $data['amount'];
        $distribution = $this->distributeGoodsUniformly($goods, $totalAmount);

        $prices = array_column($goods, 'price', 'name');
        $amount = 0;
        foreach ($distribution as $k => $v) {
            $price = $prices[$k];
            $amount += $v * $price;
        }

        print_r($distribution);
        var_dump($amount);
//        Event::getInstance()->hook('eventOrderAutoSettle', $data);
//        Task::orderAutoSettle();
//        $c = [];
//        foreach (range(0, 999) as $k){
//            $i = $k * 13 % 10;
//            $c[$i] = $c[$i] ?? 0;
//            $c[$i]++;
//            echo $k * 17 % 10 . "\n";
//        }
//        var_dump($c);
//        var_dump(date('Y-m-d H:i:s', strtotime("-".CashoutModel::PROFIT_PERIOD." day")));
//        MemberService::getInstance()->countUserNumAndScore();
//        PurchaseService::getInstance()->countOrder();
//        MemberService::getInstance()->taskCountUserData();
//        MemberProfitStatisticsService::getInstance()->statistics();
//        OrderService::getInstance()->taskOrderAutoSettle($data['date']);
//        $jwtToken = $data['jwtToken'];
            /** @var Jwt $jwt */
//        $jwt = Di::getInstance()->get('jwt');
//        $res = $jwt->validateToken($jwtToken);
//        $res = Event::getInstance()->hook('eventCountOrderTask', ['id' => 8508]);
//        $res = MemberService::getInstance()->countSubordinate(4611742);
//        var_dump($prevMonth = date('Ym', strtotime(date('Y-m-01'))- 86400));
//        $res = OrderTaskStatisticsService::getInstance()->statistics();
//        $res = OrderTaskService::getInstance()->jobCount();
//        $res = MemberService::getInstance()->countUserData(4611802);

//        $res = MemberScoreService::getInstance()->archiveRecordMonth();
//        $res = MemberProfitScoreService::getInstance()->archiveRecordMonth();
//        $res = OrderService::getInstance()->archiveRecordMonth();

//        $res = MemberProfitScoreService::getInstance()->archiveRecord();
//        $res = CommonHelper::getTableMonths();
//        var_dump($res);
//        $res = MemberProfitStatisticsService::getInstance()->statistics();
//        /** @var \App\EventHandler\CountUserHandler eventCountUser  */
//        \App\Process\LmtJob::getInstance()->createJob('eventCountUser', ["userId" => 4611802, 'time' => time()]);
//        $res = MemberService::getInstance()->taskCountUserData();
//        $res = MemberProfitScoreService::getInstance()->unionCount(4611802);
//        $res = OrderService::getInstance()->unionCount(4611802);
//        var_dump($res);
        return $this->writeJson(200, $this->request()->getRequestParam(), "success");

        $result = OrderService::getInstance()->getLists($this->request());
        return $this->writeJsonByOutput($result);
        OrderReturnedService::getInstance()->archiveOrder();
        return $this->writeJson(200, [], "success");
//        $result = MemberScoreService::getInstance()->getLists($this->request());
        $result = MemberProfitScoreService::getInstance()->getLists($this->request());
        return $this->writeJsonByOutput($result);
        return $this->writeJson(200, [$res], "success");
        $order_ids = [
            '000017d4b6a97fc4c6c907f1',
            '00003c0559a44acb6d7d9efa'
        ];
        OrderModel::create()->destroy(['id' => [$order_ids, 'in']]);
        return $this->writeJson(200, $order_ids, "success");
//        $data = OrderService::getInstance()->archiveOrder();
        $data = ShippingService::getInstance()->archiveOShipping();
        return $this->writeJson(200, $data, "success");
        $id = $this->request()['id'];
//        $res = OrderService::getInstance()->orderProfit($id);
//        $res = OrderService::getInstance()->countUnshippingOrder();
    }
    // 定义一个函数
    function myFunction() {
        static $count = 0;
        var_dump($count);
        // 函数执行的代码，每次执行时自增计数器
        $count++;

        // 如果计数器大于等于 10，或者返回值是 true，就停止执行
        if ($count >= 10 || $this->doSomething()) {
            return "Function is done\n";
        }

        // 返回 false 继续执行任务
        return false;
    }

    function doSomething() {
        // 执行任务的代码
        // 如果任务已经完成，返回 true
        return true;
    }
    function distributeGoods($goods, $totalAmount) {
        // 按价格升序排序，优先分配价格低的商品
        usort($goods, function($a, $b) {
            return $a['price'] <=> $b['price'];
        });

        $result = [];
        $remainingAmount = $totalAmount;

        // 初始化每个商品的数量为 0
        foreach ($goods as $good) {
            $result[$good['name']] = 0;
        }

        // 分配商品数量
        while ($remainingAmount > 0) {
            $allocated = false;

            foreach ($goods as &$good) {
                $price = $good['price'];
                if ($price <= $remainingAmount) {
                    // 尽可能多地分配当前商品
                    $maxQuantity = intval($remainingAmount / $price);
                    $result[$good['name']] += $maxQuantity;
                    $remainingAmount -= $maxQuantity * $price;
                    $allocated = true;
                }
            }

            // 如果没有商品可以分配，退出循环
            if (!$allocated) {
                break;
            }
        }

        return $result;
    }
    function distributeGoodsUniformly($goods, $totalAmount) {
        usort($goods, function($a, $b) {
            return $a['price'] <=> $b['price'];
        });

        $result = [];
        $remainingAmount = $totalAmount;

        // 初始化每个商品的数量为 0
        foreach ($goods as $good) {
            $result[$good['name']] = 0;
        }

        // 计算基准数量
        $averageQuantity = intval($totalAmount / array_sum(array_column($goods, 'price')));
        $averageQuantity = max(1, $averageQuantity); // 至少分配 1 个

        // 分配基准数量
        foreach ($goods as &$good) {
            $price = $good['price'];
            $maxQuantity = min($averageQuantity, intval($remainingAmount / $price));
            if ($maxQuantity > 0) {
                $result[$good['name']] += $maxQuantity;
                $remainingAmount -= $maxQuantity * $price;
            }
        }

        // 分配剩余金额
        while ($remainingAmount > 0) {
            $allocated = false;

            foreach ($goods as &$good) {
                $price = $good['price'];
                if ($price <= $remainingAmount) {
                    $result[$good['name']] += 1;
                    $remainingAmount -= $price;
                    $allocated = true;
                }
            }

            if (!$allocated) {
                break;
            }
        }

        return $result;
    }
}
